<!DOCTYPE html>
<html>
<head>
    <title>插件管理</title>
    {% include 'system/common/header.html' %}
</head>
<body class="ppress-container">
<!-- 搜索区域 -->
<div class="layui-card">
    <div class="layui-card-body">
        <form class="layui-form" action="" lay-filter="searchForm">
            <div class="layui-form-item" style="margin-bottom: unset;">
                <label class="layui-form-label">插件名称</label>
                <div class="layui-input-inline">
                    <input type="text" name="name" placeholder="" class="layui-input">
                </div>
                <label class="layui-form-label">作者</label>
                <div class="layui-input-inline">
                    <input type="text" name="author" placeholder="" class="layui-input">
                </div>
                <button class="layui-btn layui-btn-md" lay-submit lay-filter="search">
                    <i class="layui-icon layui-icon-search"></i>
                    查询
                </button>
                <button type="reset" class="layui-btn layui-btn-primary layui-btn-md">
                    <i class="layui-icon layui-icon-refresh"></i>
                    重置
                </button>
            </div>
        </form>
    </div>
</div>

<!-- 数据表格 -->
<div class="layui-card">
    <div class="layui-card-body">
        <div class="layui-form-item" style="margin-bottom: 15px;">
            <div class="layui-row">
                <div class="layui-col-md6">
                    <div class="layui-form-mid layui-word-aux">
                        <i class="layui-icon layui-icon-tips"></i>
                        提示：上传ZIP格式的插件文件，系统将自动读取插件信息
                    </div>
                </div>
                <div class="layui-col-md6" style="text-align: right;">
                    {% if authorize("system:plugin:upload") %}
                    <button class="layui-btn layui-btn-sm layui-btn-warm" onclick="uploadPlugin()">
                        <i class="layui-icon layui-icon-upload"></i>
                        上传插件
                    </button>
                    {% endif %}
                    {% if authorize("system:plugin:template") %}
                    <button class="layui-btn layui-btn-sm layui-btn-normal" onclick="showTemplate()">
                        <i class="layui-icon layui-icon-template"></i>
                        插件模板
                    </button>
                    {% endif %}
                </div>
            </div>
        </div>
        <!-- 插件列表 -->
        <table class="layui-hide" id="pluginTable" lay-filter="pluginTable"></table>
    </div>
</div>

<!-- 上传插件模态框 -->
<div id="uploadModal" style="display: none; padding: 20px;">
    <form class="layui-form" id="uploadForm">
        <div class="layui-form-item">
            <label class="layui-form-label">插件文件</label>
            <div class="layui-input-block">
                <input type="file" id="pluginFile" accept=".zip" style="display: none;">
                <button type="button" class="layui-btn layui-btn-primary" id="selectFileBtn">
                    <i class="layui-icon layui-icon-upload"></i>
                    选择ZIP文件
                </button>
                <div id="fileInfo" style="margin-top: 10px; display: none;">
                    <div class="layui-form-mid layui-word-aux">
                        <i class="layui-icon layui-icon-ok"></i>
                        <span id="fileName"></span>
                    </div>
                </div>
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label">插件名称</label>
            <div class="layui-input-block">
                <input type="text" name="plugin_name" placeholder="可选，留空则使用文件名" class="layui-input">
                <div class="layui-form-mid layui-word-aux">可选，留空则使用ZIP文件名</div>
            </div>
        </div>
        <div class="layui-form-item">
            <div class="layui-input-block">
                <div class="layui-form-mid layui-word-aux">
                    <i class="layui-icon layui-icon-tips"></i>
                    请选择包含plugin.json的插件ZIP文件，系统将自动读取插件信息
                </div>
            </div>
        </div>
    </form>
</div>

<!-- 插件模板模态框 -->
<div id="templateModal" style="display: none; padding: 20px;">
    <div class="layui-tab">
        <ul class="layui-tab-title">
            <li class="layui-this">插件结构</li>
            <li>plugin.json</li>
            <li>__init__.py</li>
            <li>example_bp.py</li>
        </ul>
        <div class="layui-tab-content">
            <div class="layui-tab-item layui-show">
                <div class="layui-form-item">
                    <label class="layui-form-label">插件结构</label>
                    <div class="layui-input-block">
                            <pre style="background: #f8f8f8; padding: 10px; border-radius: 4px;">
example_plugin/
├── templates/           # 模板文件
├── static/              # 静态文件
├── plugin.json          # 插件配置文件
├── __init__.py          # 插件初始化文件
└── example_bp.py        # 蓝图文件
                            </pre>
                    </div>
                </div>
            </div>
            <div class="layui-tab-item">
                <div class="layui-form-item">
                    <label class="layui-form-label">plugin.json</label>
                    <div class="layui-input-block">
                        <textarea id="pluginJson" class="layui-textarea" style="height: 200px;"></textarea>
                    </div>
                </div>
            </div>
            <div class="layui-tab-item">
                <div class="layui-form-item">
                    <label class="layui-form-label">__init__.py</label>
                    <div class="layui-input-block">
                        <textarea id="initPy" class="layui-textarea" style="height: 200px;"></textarea>
                    </div>
                </div>
            </div>
            <div class="layui-tab-item">
                <div class="layui-form-item">
                    <label class="layui-form-label">example_bp.py</label>
                    <div class="layui-input-block">
                        <textarea id="exampleBp" class="layui-textarea" style="height: 200px;"></textarea>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- 操作按钮模板 -->
<script type="text/html" id="pluginBar">
    {% if authorize("system:plugin:info") %}
        <a class="layui-btn layui-btn-xs" lay-event="info">详情</a>
    {% endif %}
    {% if authorize("system:plugin:toggle") %}
        {% raw %}{{# if(d.is_enabled) { }}{% endraw %}
            <a class="layui-btn layui-btn-xs layui-btn-warm" lay-event="disable">禁用</a>
        {% raw %}{{# } else { }}{% endraw %}
            <a class="layui-btn layui-btn-xs layui-btn-normal" lay-event="enable">启用</a>
        {% raw %}{{# } }}{% endraw %}
    {% endif %}
    {% if authorize("system:plugin:uninstall") %}
        <a class="layui-btn layui-btn-xs layui-btn-danger" lay-event="uninstall">卸载</a>
    {% endif %}
</script>

{% include 'system/common/footer.html' %}

<style>
/* 插件管理页面样式 */
.plugin-cards-container {
    display: flex;
    flex-wrap: wrap;
    gap: 15px;
    padding: 15px 0;
}

.plugin-card {
    width: 300px;
    border: 1px solid #e6e6e6;
    border-radius: 4px;
    background: #fff;
    transition: all 0.3s;
    position: relative;
}

.plugin-card:hover {
    box-shadow: 0 2px 8px rgba(0,0,0,0.1);
    border-color: #5FB878;
}

.plugin-card-header {
    padding: 15px;
    border-bottom: 1px solid #f2f2f2;
    position: relative;
}

.plugin-card-title {
    font-size: 16px;
    font-weight: bold;
    color: #333;
    margin-bottom: 5px;
}

.plugin-card-version {
    font-size: 12px;
    color: #999;
}

.plugin-card-status {
    position: absolute;
    top: 15px;
    right: 15px;
    padding: 2px 8px;
    border-radius: 10px;
    font-size: 12px;
    cursor: pointer;
}

.plugin-card-status.active {
    background: #5FB878;
    color: #fff;
}

.plugin-card-status.inactive {
    background: #FFB800;
    color: #fff;
}

.plugin-card-body {
    padding: 15px;
}

.plugin-card-description {
    color: #666;
    font-size: 14px;
    line-height: 1.5;
    margin-bottom: 10px;
}

.plugin-card-author {
    color: #999;
    font-size: 12px;
}

.plugin-card-footer {
    padding: 10px 15px;
    border-top: 1px solid #f2f2f2;
    display: flex;
    justify-content: space-between;
    align-items: center;
}

.plugin-card-actions {
    display: flex;
    gap: 5px;
}

.plugin-card-checkbox {
    position: absolute;
    top: 10px;
    left: 10px;
    opacity: 0.8;
    background: transparent;
    border-color: #5FB878;
}

.plugin-card-checkbox:checked {
    background: #5FB878;
    border-color: #5FB878;
}
</style>

<script>
    layui.use(['table', 'layer', 'form', 'element', 'jquery'], function () {
        var table = layui.table;
        var layer = layui.layer;
        var form = layui.form;
        var element = layui.element;
        var $ = layui.jquery;

        // 渲染表格
        table.render({
            elem: '#pluginTable',
            url: '/admin/sys/plugin_manager/list',
            cols: [[
                {field: 'id', title: 'ID', width: 80, hide: true},
                {field: 'name', title: '插件名称', width: 150},
                {field: 'version', title: '版本', width: 100},
                {field: 'description', title: '描述', width: 400},
                {field: 'author', title: '作者', width: 100},
                {field: 'is_enabled', title: '状态', width: 100, templet: function(d){
                    if(d.is_enabled){
                        return '<span class="layui-badge layui-bg-green">已启用</span>';
                    } else {
                        return '<span class="layui-badge layui-bg-gray">已禁用</span>';
                    }
                }},
                {field: 'installed_at', title: '安装时间', width: 180},
                {title: '操作', toolbar: '#pluginBar', fixed: 'right'}
            ]],
            page: true,
            limit: 20,
            limits: [10, 20, 50, 100]
        });

        // 监听搜索
        form.on('submit(search)', function(data){
            table.reload('pluginTable', {
                where: data.field
            });
            return false;
        });

        // 监听工具条
        table.on('tool(pluginTable)', function (obj) {
            var data = obj.data;
            if (obj.event === 'info') {
                showPluginInfo(data.name);
            } else if (obj.event === 'enable') {
                togglePluginStatus(data.id, data.name, true);
            } else if (obj.event === 'disable') {
                togglePluginStatus(data.id, data.name, false);
            } else if (obj.event === 'uninstall') {
                uninstallPlugin(data.name);
            }
        });

        // 显示插件详情
        function showPluginInfo(pluginName) {
            layer.open({
                type: 2,
                title: '插件详情',
                shadeClose: true,
                shade: 0.8,
                area: ['800px', '600px'],
                content: '/admin/sys/plugin_manager/info/' + pluginName
            });
        }

        // 切换插件状态（启用/禁用）
        function togglePluginStatus(pluginId, pluginName, enable) {
            var action = enable ? '启用' : '禁用';
            var confirmMsg = '确定要' + action + '插件 ' + pluginName + ' 吗？';
            
            layer.confirm(confirmMsg, function (index) {
                // 根据操作类型选择不同的接口
                var url = enable ? 
                    '/admin/sys/plugin_manager/enable/' + pluginId : 
                    '/admin/sys/plugin_manager/disable/' + pluginId;
                
                $.ajax({
                    url: url,
                    type: 'POST',
                    success: function (res) {
                        if (res.success) {
                            layer.msg(action + '成功', {icon: 1});
                            table.reload('pluginTable');
                        } else {
                            layer.msg(action + '失败: ' + res.msg, {icon: 2});
                        }
                    },
                    error: function () {
                        layer.msg('请求失败', {icon: 2});
                    }
                });
                layer.close(index);
            });
        }

        // 卸载插件
        function uninstallPlugin(pluginName) {
            layer.confirm('确定要卸载插件 ' + pluginName + ' 吗？此操作不可恢复！', function (index) {
                $.ajax({
                    url: '/admin/sys/plugin_manager/uninstall',
                    type: 'POST',
                    contentType: 'application/json',
                    data: JSON.stringify({
                        plugin_name: pluginName
                    }),
                    success: function (res) {
                        if (res.success) {
                            layer.msg('卸载成功', {icon: 1});
                            table.reload('pluginTable');
                        } else {
                            layer.msg('卸载失败: ' + res.msg, {icon: 2});
                        }
                    },
                    error: function () {
                        layer.msg('请求失败', {icon: 2});
                    }
                });
                layer.close(index);
            });
        }

        // 上传插件
        window.uploadPlugin = function(){
            layer.open({
                type: 1,
                title: '上传插件',
                area: ['500px', '350px'],
                content: `
                    <div class="layui-form" style="padding: 20px;">
                        <div class="layui-form-item">
                            <label class="layui-form-label">插件文件</label>
                            <div class="layui-input-block">
                                <input type="file" id="pluginFile" accept=".zip" style="display: none;">
                                <button type="button" class="layui-btn layui-btn-primary" id="selectFileBtn">
                                    <i class="layui-icon layui-icon-upload"></i>
                                    选择ZIP文件
                                </button>
                                <div id="fileInfo" style="margin-top: 10px; display: none;">
                                    <div class="layui-form-mid layui-word-aux">
                                        <i class="layui-icon layui-icon-ok"></i>
                                        <span id="fileName"></span>
                                    </div>
                                </div>
                            </div>
                        </div>
                        <div class="layui-form-item">
                            <label class="layui-form-label">插件名称</label>
                            <div class="layui-input-block">
                                <input type="text" id="pluginName" placeholder="可选，留空则使用文件名" class="layui-input">
                                <div class="layui-form-mid layui-word-aux">可选，留空则使用ZIP文件名</div>
                            </div>
                        </div>
                        <div class="layui-form-item">
                            <div class="layui-input-block">
                                <div class="layui-form-mid layui-word-aux">
                                    <i class="layui-icon layui-icon-tips"></i>
                                    请选择包含plugin.json的插件ZIP文件，系统将自动读取插件信息
                                </div>
                            </div>
                        </div>
                        <div class="layui-form-item">
                            <div class="layui-input-block">
                                <button type="button" class="layui-btn" id="submitUploadBtn">
                                    <i class="layui-icon layui-icon-upload"></i>
                                    上传插件
                                </button>
                                <button type="button" class="layui-btn layui-btn-primary" id="cancelUploadBtn">
                                    取消
                                </button>
                            </div>
                        </div>
                    </div>
                `,
                success: function(layero, index){
                    // 使用事件委托绑定选择文件按钮事件
                    $(layero).on('click', '#selectFileBtn', function(){
                        $(layero).find('#pluginFile').click();
                    });

                    // 监听文件选择
                    $(layero).on('change', '#pluginFile', function(){
                        var file = this.files[0];
                        if(file){
                            if(file.name.toLowerCase().endsWith('.zip')){
                                $(layero).find('#fileName').text(file.name + ' (' + (file.size / 1024 / 1024).toFixed(2) + ' MB)');
                                $(layero).find('#fileInfo').show();
                            } else {
                                layer.msg('请选择ZIP格式的文件', {icon: 2});
                                this.value = '';
                            }
                        }
                    });

                    // 绑定提交按钮事件
                    $(layero).on('click', '#submitUploadBtn', function(){
                        submitPluginUpload(layero);
                    });

                    // 绑定取消按钮事件
                    $(layero).on('click', '#cancelUploadBtn', function(){
                        layer.close(index);
                    });
                }
            });
        };

        // 提交插件上传
        window.submitPluginUpload = function(layero){
            var file = $(layero).find('#pluginFile')[0].files[0];

            if(!file){
                layer.msg('请选择插件文件', {icon: 2});
                return;
            }

            // 检查文件大小（限制为50MB）
            if(file.size > 50 * 1024 * 1024){
                layer.msg('文件大小不能超过50MB', {icon: 2});
                return;
            }

            var formData = new FormData();
            formData.append('file', file);

            var pluginName = $(layero).find('#pluginName').val();
            if(pluginName){
                formData.append('plugin_name', pluginName);
            }

            // 显示上传进度
            var loadIndex = layer.load(1, {
                shade: [0.1, '#fff']
            });

            $.ajax({
                url: '/admin/sys/plugin_manager/upload',
                type: 'POST',
                data: formData,
                processData: false,
                contentType: false,
                success: function(res){
                    layer.close(loadIndex);
                    if(res.success){
                        layer.msg('插件上传成功', {icon: 1});
                        table.reload('pluginTable');
                        layer.closeAll();
                    } else {
                        layer.msg('插件上传失败: ' + res.msg, {icon: 2});
                    }
                },
                error: function(){
                    layer.close(loadIndex);
                    layer.msg('请求失败', {icon: 2});
                }
            });
        };

        // 显示插件模板
        window.showTemplate = function() {
            $.ajax({
                url: '/admin/sys/plugin_manager/template',
                type: 'GET',
                success: function (res) {
                    if (res.success) {
                        var data = res.data;
                        $('#pluginJson').val(JSON.stringify(data['plugin.json'], null, 2));
                        $('#initPy').val(data['__init__.py']);
                        $('#exampleBp').val(data['example_bp.py']);

                        layer.open({
                            type: 1,
                            title: '插件模板',
                            area: ['800px', '600px'],
                            content: $('#templateModal'),
                            success: function () {
                                element.render('tab');
                            }
                        });
                    } else {
                        layer.msg('获取模板失败: ' + res.msg, {icon: 2});
                    }
                },
                error: function () {
                    layer.msg('请求失败', {icon: 2});
                }
            });
        };


    });
</script>

<style>
/* 插件管理页面样式 */
.plugin-cards-container {
    display: flex;
    flex-wrap: wrap;
    gap: 15px;
    padding: 15px 0;
}

.plugin-card {
    width: 300px;
    border: 1px solid #e6e6e6;
    border-radius: 4px;
    background: #fff;
    transition: all 0.3s;
    position: relative;
}

.plugin-card:hover {
    box-shadow: 0 2px 8px rgba(0,0,0,0.1);
    border-color: #5FB878;
}

.plugin-card-header {
    padding: 15px;
    border-bottom: 1px solid #f2f2f2;
    position: relative;
}

.plugin-card-title {
    font-size: 16px;
    font-weight: bold;
    color: #333;
    margin-bottom: 5px;
}

.plugin-card-version {
    font-size: 12px;
    color: #999;
}

.plugin-card-status {
    position: absolute;
    top: 15px;
    right: 15px;
    padding: 2px 8px;
    border-radius: 10px;
    font-size: 12px;
    cursor: pointer;
}

.plugin-card-status.active {
    background: #5FB878;
    color: #fff;
}

.plugin-card-status.inactive {
    background: #FFB800;
    color: #fff;
}

.plugin-card-body {
    padding: 15px;
}

.plugin-card-description {
    color: #666;
    font-size: 14px;
    line-height: 1.5;
    margin-bottom: 10px;
}

.plugin-card-author {
    color: #999;
    font-size: 12px;
}

.plugin-card-footer {
    padding: 10px 15px;
    border-top: 1px solid #f2f2f2;
    display: flex;
    justify-content: space-between;
    align-items: center;
}

.plugin-card-actions {
    display: flex;
    gap: 5px;
}

.plugin-card-checkbox {
    position: absolute;
    top: 10px;
    left: 10px;
    opacity: 0.8;
    background: transparent;
    border-color: #5FB878;
}

.plugin-card-checkbox:checked {
    background: #5FB878;
    border-color: #5FB878;
}
</style>
</body>
</html> 